from django.shortcuts import render, redirect, HttpResponse
from rbac.form.permission import RolesForm
from rbac import models


def roles_list(request):
    '''
    权限之角色列表展示
    :param request:
    :return:
    '''
    # 1.查询当前用户表的所有角色quesryset
    if request.method == 'GET':
        roles_obj = models.Role.objects.all()
        return render(request, 'rbac/roles_list.html', locals())


def roles_add(request):
    '''
    角色添加
    :param request:
    :return:
    '''
    if request.method == 'GET':
        form = RolesForm()
        return render(request, 'rbac/roles_add.html', locals())
    form = RolesForm(data=request.POST)
    if form.is_valid():
        form.save()
        return redirect('roles_list')
    return render(request, 'rbac/roles_add.html', locals())


def roles_edit(request, roles_id):
    '''
    角色编辑
    :param request:
    :return:
    '''
    roles_obj = models.Role.objects.filter(id=roles_id).first()
    if request.method == 'GET':
        form = RolesForm(instance=roles_obj)
        return render(request, 'rbac/roles_edit.html', locals())
    form = RolesForm(data=request.POST, instance=roles_obj)
    if form.is_valid():
        form.save()
        return redirect('roles_list')
    return render(request, 'rbac/roles_edit.html')


def roles_del(request, roles_id):
    '''
    角色删除
    :param request:
    :return:
    '''
    roles_obj = models.Role.objects.filter(id=roles_id).first().delete()
    return redirect('roles_list')